﻿using IMServer.Models;
using MongoDB.Driver;
using System;
using System.Threading.Tasks;

namespace IMServer.Database
{
    public class MongoDBContext
    {
        private static readonly MongoDBContext _instance = new MongoDBContext();
        private readonly string _connectionString = "mongodb://***:***@***";
        private readonly string _databaseName = "***";
        private readonly IMongoDatabase _database;

        // 私有构造函数，防止外部实例化
        private MongoDBContext()
        {
            try
            {
                var client = new MongoClient(_connectionString);
                _database = client.GetDatabase(_databaseName);
                
                // 使用异步方法初始化集合
                Task.WhenAll(
                    _database.CreateCollectionAsync("Users"),
                    _database.CreateCollectionAsync("Groups"), 
                    _database.CreateCollectionAsync("MessageBoxes"),
                    _database.CreateCollectionAsync("PendingRequestBoxes")
                ).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                // 添加更详细的错误信息
                throw new InvalidOperationException($"MongoDB初始化失败: {ex.Message}", ex);
            }
        }

        // 公共静态属性，用于获取唯一实例
        public static MongoDBContext Instance
        {
            get { return _instance; }
        }

        // 简化属性语法
        public IMongoCollection<User> Users => _database.GetCollection<User>("Users");
        public IMongoCollection<Group> Groups => _database.GetCollection<Group>("Groups");
        public IMongoCollection<MessageBox> MessageBoxes => _database.GetCollection<MessageBox>("MessageBoxes");
        public IMongoCollection<PendingRequestBox> PendingRequestBoxes => _database.GetCollection<PendingRequestBox>("PendingRequestBoxes");
    }
}